package cn.vawn.exam.controller;

import cn.vawn.base.consts.AppConsts;
import cn.vawn.base.controller.BaseController;
import cn.vawn.base.dto.PageDTO;
import cn.vawn.base.dto.ResponseResult;
import cn.vawn.base.util.DateUtil;
import cn.vawn.base.util.StringArrayUtil;
import cn.vawn.exam.entity.*;
import cn.vawn.exam.service.*;
import cn.vawn.exam.service.exception.DataNotFoundException;
import cn.vawn.medical.service.IOrganizationService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Controller
@RequestMapping("exam")
public class PaperController extends BaseController {

	private static Logger logger = LoggerFactory.getLogger(PaperController.class);

	@Resource
	private IPaperService paperService;

	@Resource
	private IPaperTypeService paperTypeService;

	@Resource
	private IAnswerService answerService;

	@Resource
	private IQuestionsService questionsService;

	@Resource
	private IQuestionSerialService questionSerialService;

	@Resource
	private ILocalUnitermService localUnitermService;

	@Resource
	private IOrganizationService organizationService;

	@RequestMapping(value = "/getAllPaper", method = RequestMethod.GET)
	@ResponseBody
	public ResponseResult<PageDTO> getAllPaper(HttpServletRequest request, HttpServletResponse response) {
		//token验证
//		String token = request.getParameter("token");
//		System.out.println(token);

		logger.info("try to get all Paper");

		PageDTO paperList =  paperService.getAllPaper(getPage());

		ResponseResult<PageDTO> rr =
				new ResponseResult<>(AppConsts.RESPONSE_STATUS_SUCCESS, paperList);

		return rr;
	}

	@RequestMapping(value = "/getAllType", method = RequestMethod.GET)
	@ResponseBody
	public ResponseResult<List<PaperType>> getAllPaperType(String token) {
		//token��֤

		ResponseResult<List<PaperType>> rr =
				new ResponseResult<>(1, paperService.getAllPaperType());

		return rr;
	}

	@RequestMapping(value = "/getPartPaper", method = RequestMethod.GET)
	@ResponseBody
	public ResponseResult<PageDTO> getPartPaper(String token, String paperName, String paperType, String startTime, String endTime) {
		//token��֤
		logger.info("try to get paper by paperName + " + paperName + ",paperType = " + paperType +
					",startTime = " + startTime + ",endTime = " + endTime);

		ResponseResult<PageDTO> rr =
				new ResponseResult<>(1, paperService.getPartPaper(getPage(), paperName, paperType, startTime, endTime));

		return rr;
	}

	@RequestMapping(value = "/dltPaper", method = RequestMethod.POST)
	@ResponseBody
	public ResponseResult<Void> dltPaper(HttpServletRequest request) {
		//token��֤
//		String token = request.getParameter("token");
//		System.out.println(token);
		String paperId = request.getParameter("paperId");
		logger.info("try to delete paper by paperId = " + paperId);

		ResponseResult<Void> rr = null;
		try {
//			System.out.println(paperId);
			paperService.deletePaper(Integer.parseInt(paperId));
			rr = new ResponseResult<>(1, "删除成功");
		} catch (DataNotFoundException e) {
			rr = new ResponseResult<>(0, e.getMessage());
		}

		return rr;
	}

	@RequestMapping(value = "/getAllPaperName", method = RequestMethod.GET)
	@ResponseBody
	public ResponseResult<List<Map<String, Object>>> getAllPaperName(String token) {
		//token��֤

		ResponseResult<List<Map<String, Object>>> rr =
				new ResponseResult<List<Map<String, Object>>>(1, paperService.getAllPapaerName());

		return rr;
	}

	@RequestMapping(value = "/getPaperAllContent", method = RequestMethod.GET)
	@ResponseBody
	public ResponseResult<List<Map<String, Object>>> getPaperAllContent(String token, Integer paperId) {
		//token��֤
		logger.info("try to get paper's all content by paperId = " + paperId);

		List<Map<String, Object>> datas =
				paperService.getPaperAllConetnt(paperId);
		System.out.println(datas);
		ResponseResult<List<Map<String, Object>>> rr = new ResponseResult<List<Map<String, Object>>>(1, datas);

		return rr;
	}

	@RequestMapping(value = "/mdfPaper", method = RequestMethod.POST)
	@ResponseBody
	public ResponseResult<Void> mdfPaper(@RequestBody String data) {
		JSONObject object = JSONObject.fromObject(data);

		String name = object.getString("name");
		String type = object.getString("type");
		int paperId = object.getInt("paperId");

		//
		JSONArray questionsArray = object.getJSONArray("questions");
		List<QuestionSerial> questionSerials = new ArrayList<>();

		StringBuilder questionBuilder = new StringBuilder();

		//����questionsArray
		for (int i = 0; i < questionsArray.size(); i++) {
			//
			JSONObject questionsObj = (JSONObject) questionsArray.get(i);

			int questionsId = questionsObj.getInt("questionsId");

			int serialNum = questionsObj.getInt("serialNum");

			QuestionSerial questionSerial = new QuestionSerial();
			questionSerial.setPaperId(paperId);
			questionSerial.setQuestionsId(questionsId);
			questionSerial.setSerial(serialNum);

			questionSerials.add(questionSerial);

			questionBuilder.append(questionsId);
			if (i != questionsArray.size() - 1) {
				questionBuilder.append(",");
			}

			//
			JSONArray answerArray = questionsObj.getJSONArray("answers");
			List<Answer> answers = new ArrayList<>();

			StringBuilder answerBuilder = new StringBuilder();

			//
			for (int j = 0; j < answerArray.size(); j++) {
				//
				JSONObject answerObj = (JSONObject) answerArray.get(i);

				int answerId = answerObj.getInt("answerId");
				String localUnitermIds = answerObj.getString("localUnitermIds");
				String unUsedSerialNumIds = answerObj.getString("unUsedSerialNumIds");
				String answerContent = answerObj.getString("content");

				answerBuilder.append(answerId);
				if (j != answerArray.size() - 1) {
					answerBuilder.append(",");
				}

				Answer answer = new Answer();
				answer.setId(answerId);
				answer.setContent(answerContent);
				answer.setLocalUnitermIds(localUnitermIds);
				answer.setUnUsedSerialNumIds(unUsedSerialNumIds);

				answers.add(answer);
			}

			answerService.batchUpdateAnswers(answers);

		}

		Paper paper = new Paper();
		paper.setId(paperId);
		paper.setName(name);
		paper.setQuestionsIds(questionBuilder.toString());
		paper.setType(type);

		ResponseResult<Void> rr = null;
		Date now = new Date();
		Integer userId = getCurrentUser().getId();
		if (paperId == 0) {
			//ִ执行添加问卷操作
			paper.setCreatedBy(userId);
			paper.setCreatedTime(now);
			paperService.addPaper(paper);

			for (QuestionSerial questionSerial : questionSerials) {
				questionSerial.setPaperId(paper.getId());
			}

			rr = new ResponseResult<>(1, "问卷添加成功");
		} else {
			//ִ执行跟新操作
			try {
				paperService.updatePaper(paper, userId);
				rr = new ResponseResult<>(2, "问卷更新成功");
			} catch (DataNotFoundException e) {
				rr = new ResponseResult<>(0, e.getMessage());
			}
		}
		for (QuestionSerial questionSerial : questionSerials) {
			System.out.println(questionSerial);
		}
		questionSerialService.updateOrInsertQuestionSerial(questionSerials);

		return rr;
	}

	//根据机构查询问卷
	@RequestMapping(value = "/getDefaultPaper", method = RequestMethod.GET)
	@ResponseBody
	public ResponseResult<List<Map<String, Object>>> getDefaultPaper(String token, Integer organizationId) {
		//token验证
		logger.info("getDefaultPaper is called");

		//根据机构id查询问卷id
//		int paperId = organizationService.getDefaultPaperIdByOrgId(organizationId);
		int paperId = 1;

		//根据问卷id查询问卷信息
		Paper paper = paperService.getPaperById(paperId);
		List<Map<String, Object>> questionsList = new ArrayList<>();
		if(paper != null){
			//获取Paper对象中的QuestionsIds
			String questionsIds = paper.getQuestionsIds();
			//将字符串转换成集合
			List<Integer> questionIdsList = StringArrayUtil.stringArrToList(questionsIds.split(","));

			//根据id集合批量查询问卷中的问题
			List<Questions> questionss = questionsService.batchSelectQuestionsByIds(questionIdsList);

			//遍历集合
			for (Questions q : questionss) {
				Map<String, Object> map = new HashedMap();
				map.put("questionsId", q.getId());
				map.put("content", q.getContent());
				map.put("optionType", q.getOptionType());
				map.put("finish", false);

				String answerIds = q.getAnswerIds();
				List<Integer> answerIdsList = StringArrayUtil.stringArrToList(answerIds.split(","));
				//根据id集合批量查询问题中的选项答案
				List<Answer> answers = answerService.batchSelectAnswers(answerIdsList);
				map.put("answers", answers);

				//根据问卷id和问题id查询问题的序号
				QuestionSerial qSerial = new QuestionSerial();
				qSerial.setPaperId(paperId);
				qSerial.setQuestionsId(q.getId());
				QuestionSerial questionSerial = questionSerialService.getQuestionSerial(qSerial);
				//将问题序号添加到map集合中
				if (questionSerial != null){
					map.put("questionSerial", questionSerial.getSerial());
				}

				//将map集合添加到List集合中
				questionsList.add(map);
			}
		}

		ResponseResult<List<Map<String, Object>>> rr = new ResponseResult<>(1, questionsList);

		return rr;
	}

	//根据提交的问卷答案选项返回单项增项
	@RequestMapping(value = "/getUnitermsByAnswers", method = RequestMethod.POST)
	@ResponseBody
	public ResponseResult<Map<String, Object>> getUnitermsByAnswers(@RequestBody String data) {
		logger.info("try to get uniterm by answers");
		//获取token，进行token验证
		JSONObject object = JSONObject.fromObject(data);
		String token = object.getString("token");
		System.out.println(token);

		//获取参数信息
		String organizationId = object.getString("organizationId");
		JSONArray packageIdArray =  object.getJSONArray("packageId");
		JSONArray answersIdArray = object.getJSONArray("answerId");

		//创建返回结果的map集合
		Map<String, Object> resulltMap = new HashedMap();
/*		resulltMap.put("organizationId", organizationId);

//		List<Package> packageList = new ArrayList<>();

		//创建集合存储所有套餐中的单项id
		List<Integer> allUnitermIds = new ArrayList<>();
		//创建集合存储除了第一个套餐外的所欲套餐的单项id
		List<Integer> otherUnitermIds = null;

		//判断packageIdArray长度，做不同的逻辑处理
		if(packageIdArray.size() == 1) {
			//只选择了一个套餐
			int packageId = (int)packageIdArray.get(0);

//			Package p = packageService.getPackageById(packageId);
			//packageList.add(p);
			//根据套餐id获取该套餐中的所有单项id字符串
			//String unitermids = p.getUnitermIds();
			String unitermids = "";
			//将字符串转换成List集合,赋值给allUnitermIds
			allUnitermIds = StringArrayUtil.stringArrToList(unitermids.split(","));
		} else {
			otherUnitermIds = new ArrayList<>();

			//选择了多个套餐，先获取第一个套餐中的所有单项
			int first_packageId = (int)packageIdArray.get(0);
			//Package p = packageService.getPackageById(packageId);

			//根据套餐id获取该套餐中的所有单项id字符串
			//String unitermids = p.getUnitermIds();
			String unitermids = "";
			//将字符串转换成List集合，然后执行批量查询操作查询出套餐中包含的单项
			List<Integer> firsUnitermIdsList = StringArrayUtil.stringArrToList(unitermids.split(","));
			for (Integer in: firsUnitermIdsList){
				allUnitermIds.add(in);
			}
			//遍历packageIdArray，获取其他套餐中的单项id集合
			Set<Integer> otherUnitermIdsSet = new HashSet<>();
			for (int i = 1; i < packageIdArray.size(); i++) {
				int pachageId = (int)packageIdArray.get(i);
				//根据套餐id获取该套餐中的所有单项id字符串
				//Package p = packageService.getPackageById(packageId);
				//String unitermids = p.getUnitermIds();
				//将字符串转换成List集合
				//List<Integer> oterUnitermIdsList = StringArrayUtil.stringArrToList(unitermids.split(","));
				//判断与firsUnitermIdsList是否存在交集
				//if(judgeList(firsUnitermIdsList，unitermIdsList)) {
				//	packageList.add(p);
				// continue;
				//}

				//遍历集合，将集合中的数据添加到othorUnitermIdsSet中
			}
			//遍历othorUnitermIdsSet集合
			Iterator<Integer> iterator = otherUnitermIdsSet.iterator();
			while (iterator.hasNext()) {
				//判断firsUnitermIdsList中是否包含othorUnitermIdsSet中的元素
				int id = iterator.next();
				if (firsUnitermIdsList.contains(id)) {
					//将该元素删除
					iterator.remove();
				} else {
					otherUnitermIds.add(id);
					allUnitermIds.add(id);
				}
			}
		}*/

//		resulltMap.put("packageList", packageList);


		//遍历answersIdArray，获取本地单项的id集合
		Set<Integer> localUnitermIdsSet = new HashSet<>();
		for (int i = 0;i < answersIdArray.size();i++) {
			//获取参数中的answerId
			String str = (String) answersIdArray.get(i);
			int answerId = Integer.parseInt(str);
			//根据答案id获取关联的本地单项的id字符串
			String localUnitermIds = answerService.getLocalUnitermIds(answerId);
			if("".equals(localUnitermIds) || localUnitermIds == null) {
				continue;
			}
			//将字符串转换成list集合
			List<Integer> idList = StringArrayUtil.stringArrToList(localUnitermIds.split(","));
			//遍历集合，将数据添加到Set集合中
			for (Integer in: idList) {
				localUnitermIdsSet.add(in);
			}
		}

		List<LocalUniterm> localUnitermList = new ArrayList<>();
		for (Integer in : localUnitermIdsSet) {
			localUnitermList.add(localUnitermService.getLocalUniterm(in));
		}
		resulltMap.put("uniterms", localUnitermList);


		/*//批量操作，将otherUnitermIds中的单项转换成本地单项
		if (otherUnitermIds != null && otherUnitermIds.size() > 0) {
			//List<LocalUniterm> localUniterms_package = unitermService.turnUnitermToLocal(otherUnitermIds);
			//resultMap.put("localUniterms_package", localUniterms_package);
		}
		//批量操作，将localUnitermIdsSet中的本地单项id转换成机构单项id
		List<Integer> unitermIdsList = new ArrayList<>();

		//批量查询allUnitermIds中的单项的包含项
		List<String> existIdsStrList = new ArrayList<>();
		Set<Integer> existIdsSet = new HashSet<>();
		for (String  str : existIdsStrList) {
			for (Integer in : StringArrayUtil.stringArrToList(str.split(","))) {
				existIdsSet.add(in);
			}
		}
		//批量查询allUnitermIds中的单项的排他项
		List<String> excludeIdsStrList = new ArrayList<>();
		Set<Integer> excludeIdsSet = new HashSet<>();
		for (String  str : excludeIdsStrList) {
			for (Integer in : StringArrayUtil.stringArrToList(str.split(","))) {
				excludeIdsSet.add(in);
			}
		}*/

		/*Iterator<Integer> iterator = unitermIdsList.iterator();
		while (iterator.hasNext()) {
			int id = iterator.next();
			//判断问卷结果中的单项是否存在套餐的单项中
			if(allUnitermIds.contains(id)) {
				iterator.remove();
			} else {
				//判断问卷中的单项是否存在套餐的单项的包含项中
				if (existIdsSet.contains(id)) {
					iterator.remove();
					continue;
				}
				//判断问卷中的单项是否存在套餐的单项的排他项中
				if (excludeIdsSet.contains(id)) {
					iterator.remove();
				}
			}
		}*/
		/*//将unitermIdsList转换成本地单项
		if(unitermIdsList != null && unitermIdsList.size() > 0) {
			//List<LocalUniterm> localUniterms_answers = unitermService.turnUnitermToLocal(otherUnitermIds);
			//resultMap.put("localUniterms_answers", localUniterms_answers);
		}*/



		//模拟数据
//		Map<String, Object> resulltMap = new HashedMap();
		resulltMap.put("organizationId", 1);

		Map<String, Object> map = new HashedMap();
		map.put("packageName", "基本体检套餐A");
		map.put("cost", 80.00);
		List<Map<String, Object>> packages = new ArrayList<>();
		packages.add(map);
		resulltMap.put("packageList", packages);

		List<Map<String, Object>> otherPackageUniterms = new ArrayList<>();
		map = new HashedMap();
		map.put("unitermName", "血压检查");
		map.put("cost", 80.00);
		otherPackageUniterms.add(map);
		resulltMap.put("otherPackageUniterms", otherPackageUniterms);

//		List<Map<String, Object>> uniterms = new ArrayList<>();
//		map = new HashedMap();
//		map.put("unitermName", "血压检查");
//		map.put("cost", 80.00);
//		uniterms.add(map);
//		resulltMap.put("uniterms", uniterms);

		ResponseResult<Map<String, Object>> rr = new ResponseResult<>(1, resulltMap);

		return rr;
	}

	//判断两个集合是否存在交集
	public boolean judgeList(List<Integer> list1, List<Integer> list2) {
		//创建一个Set集合
		Set<Integer> set = new HashSet<>();
		for (Integer in : list1) {
			set.add(in);
		}
		for (Integer in : list2) {
			set.add(in);
		}
		if (list1.size() + list2.size() != set.size()) {
			return false;
		}
		return true;
	}

	@RequestMapping(value = "/getPaperById", method = RequestMethod.POST)
	@ResponseBody
	public ResponseResult<Map<String, Object>> getPaperById(HttpServletRequest request) {
		//token验证
//		String token = request.getParameter("token");
//		System.out.println(token);

		String paperId = request.getParameter("paperId");
		logger.info("try to get paper by paperId = " + paperId);

		//根据问卷id查询问卷信息
		Paper paper = paperService.getPaperById(Integer.parseInt(paperId));

		//获取Paper对象中的QuestionsIds
		String questionsIds = paper.getQuestionsIds();
		//将字符串转换成集合
		List<Integer> questionIdsList = StringArrayUtil.stringArrToList(questionsIds.split(","));

		//根据id集合批量查询问卷中的问题
		List<Questions> questionss = questionsService.batchSelectQuestionsByIds(questionIdsList);

		Map<String, Object> resultMap = new HashedMap();
		resultMap.put("paperName", paper.getName());
		resultMap.put("classType", paper.getType());

		List<Map<String, Object>> questionsList = new ArrayList<>();
		//遍历集合
		for (Questions q : questionss) {
			Map<String, Object> map = new HashedMap();
			map.put("questionsId", q.getId());
			map.put("content", q.getContent());
			map.put("optionType", q.getOptionType());
			map.put("finish", false);

			String answerIds = q.getAnswerIds();
			List<Integer> answerIdsList = StringArrayUtil.stringArrToList(answerIds.split(","));
			//根据id集合批量查询问题中的选项答案
			List<Answer> answers = answerService.batchSelectAnswers(answerIdsList);
			map.put("answers", answers);

			//根据问卷id和问题id查询问题的序号
			QuestionSerial qSerial = new QuestionSerial();
			qSerial.setPaperId(Integer.parseInt(paperId));
			qSerial.setQuestionsId(q.getId());
			QuestionSerial questionSerial = questionSerialService.getQuestionSerial(qSerial);
			//将问题序号添加到map集合中
			map.put("questionSerial", questionSerial.getSerial());

			//将map集合添加到List集合中
			questionsList.add(map);
		}

		resultMap.put("questionList", questionsList);

		ResponseResult<Map<String, Object>> rr = new ResponseResult<>(1, resultMap);

		return rr;
	}

	@RequestMapping(value = "/addPaper", method = RequestMethod.POST)
	@ResponseBody
	public ResponseResult<Void> addPaper(@RequestBody String data) {
		//token验证
		JSONObject object = JSONObject.fromObject(data);
		String token = object.getString("token");
		System.out.println(token);

		//获取参数值
//		String paperId = object.getString("paperId");
		String paperName = object.getString("newPaperName");
		JSONArray questionIdsList = object.getJSONArray("questionIds");
		JSONArray serialList = object.getJSONArray("serials");
		String classType = object.getString("classType");

		logger.info("add paper by parameter : newPaperName = " + paperName + ",questionIdList = " +
					questionIdsList +",classType = " + classType + ",serialList = " + serialList);

		Paper paper = new Paper();

//		if(paperId != null && !"".equals(paperId)) {
//			paper.setPaperId(Integer.parseInt(paperId));
//		}

		paper.setName(paperName);
		paper.setType(classType);
		paper.setCreatedTime(new Date());

		StringBuilder answerIds = new StringBuilder();

		List<QuestionSerial> questionSerials = new ArrayList<>();

		for (int i = 0; i < questionIdsList.size(); i++) {
			String questionId = (String) questionIdsList.get(i);

			QuestionSerial serial = new QuestionSerial();
			serial.setQuestionsId(Integer.parseInt(questionId));
			serial.setSerial((int)serialList.get(i));
			questionSerials.add(serial);

			answerIds.append(questionId).append(",");
		}

		String answerIdsStr = answerIds.toString();
		answerIdsStr = answerIdsStr.substring(0,answerIdsStr.length() - 1);
		paper.setQuestionsIds(answerIdsStr);

		paperService.insertPaper(paper, questionSerials);

		System.out.println(paper.getId() + "*****");

		return new ResponseResult<>(1,"添加成功");
	}

	@RequestMapping(value = "/updatePaper", method = RequestMethod.POST)
	@ResponseBody
	public ResponseResult<Void> updatePaper(@RequestBody String data) {
		//token验证
		JSONObject object = JSONObject.fromObject(data);
		String token = object.getString("token");
		System.out.println(token);

		//获取参数值
		String paperId = object.getString("paperId");
		JSONArray questionIdsList = object.getJSONArray("questionIds");
		JSONArray serialList = object.getJSONArray("serials");
		String classType = object.getString("classType");

		logger.info("update paper by parameter ：paperId = " + paperId + ",serialList = " + serialList +
					",questionIdsList = " + questionIdsList + ",classType = " + classType);

		Paper paper = new Paper();
		paper.setId(Integer.parseInt(paperId));
		paper.setType(classType);

		StringBuilder answerIds = new StringBuilder();

		List<QuestionSerial> questionSerials = new ArrayList<>();

		for (int i = 0; i < questionIdsList.size(); i++) {
			String questionId = (String) questionIdsList.get(i);

			QuestionSerial serial = new QuestionSerial();
			serial.setQuestionsId(Integer.parseInt(questionId));
//            String s = (String)serialList.get(i);
			serial.setSerial((int)serialList.get(i));
			serial.setPaperId(Integer.parseInt(paperId));
			questionSerials.add(serial);

			answerIds.append(questionId).append(",");
		}

		String answerIdsStr = answerIds.toString();
		answerIdsStr = answerIdsStr.substring(0,answerIdsStr.length() - 1);
		System.out.println(answerIdsStr);
		paper.setQuestionsIds(answerIdsStr);

		paperService.updatePaper(paper, questionSerials);


		return new ResponseResult<>(1,"修改成功");
	}

	@RequestMapping(value = "/updateSerial", method = RequestMethod.POST)
	@ResponseBody
	public ResponseResult<Void> updateSerial(@RequestBody String data) {
		JSONObject object = JSONObject.fromObject(data);
		//token验证
//		String token = object.getString("token");
//		System.out.println(token);

		String paperId = object.getString("paperId");
		String content = object.getString("paperContent");
		String classType = object.getString("classType");
		JSONArray array = object.getJSONArray("answerSerial");

		logger.info("update paper serial by parameter : paperId = " + paperId + ",content = " +
					content + ",classType = " + classType + ",array = " + array);

		Paper paper = new Paper();
		paper.setId(Integer.parseInt(paperId));
		paper.setName(content);
		paper.setType(classType);
		Integer userId = getCurrentUser().getId();
		paperService.updatePaper(paper,userId);

		List<String> serials = new ArrayList<>();

		for(int i = 0; i < array.size(); i++) {
			String serial = (String) array.get(i);
			serials.add(serial);
		}

		paperService.updateAnswer(serials);

		ResponseResult<Void> rr = new ResponseResult<>(1,"编辑成功");

		return rr;
	}

	@RequestMapping(value = "/paper-type", method = RequestMethod.GET)
	@ResponseBody
	public ResponseResult<PageDTO> searchPaperType(@RequestParam(value = "typeName", required = false) String typeName,
												   @RequestParam(value = "startTime", required = false) String startTime,
												   @RequestParam(value = "endTime", required = false) String endTime) {
		logger.info("try to search paper type by typeName: " + typeName + ", startTime: " + startTime + ", endTime: " + endTime);
		Date startDate = null;
		if (!"".equals(startTime)) {
			startDate = DateUtil.parseDate(startTime);
		}
		Date endDate = null;
		if (!"".equals(endTime)) {
			endDate = DateUtil.parseDate(endTime);
		}
		PageDTO paperTypeList = paperTypeService.searchPaperType(getPage(), typeName, startDate, endDate);
		ResponseResult<PageDTO> rr = new ResponseResult<>(AppConsts.RESPONSE_STATUS_SUCCESS, paperTypeList);
		return rr;
	}

	@RequestMapping(value = "/paper-type/{id}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseResult<PaperType> getPaperTypeById(@PathVariable("id") Integer paperTypeId) {
		logger.info("try to get paper type by paperTypeId: " + paperTypeId);
		PaperType paperType = paperTypeService.selectById(paperTypeId);
		ResponseResult<PaperType> rr = new ResponseResult<>(AppConsts.RESPONSE_STATUS_SUCCESS, paperType);
		return rr;
	}

	@RequestMapping(value = "/paper-type", method = RequestMethod.POST)
	@ResponseBody
	public ResponseResult<Integer> createPaperType(@RequestBody PaperType paperType) {
		logger.info("try to create paper type by paperType: " + paperType);
		paperType.setId(null);
		paperType.setStatus(0);
		paperType.setIsDeleted(false);
		paperType.setCreatedBy(getCurrentUser().getId());
		paperType.setCreatedTime(new Date());
		paperTypeService.insert(paperType);
		ResponseResult<Integer> rr = new ResponseResult<>(AppConsts.RESPONSE_STATUS_SUCCESS, 1);
		return rr;
	}

	@RequestMapping(value = "/paper-type", method = RequestMethod.PUT)
	@ResponseBody
	public ResponseResult<Integer> updatePaperType(@RequestParam("paperTypeId") Integer paperTypeId,
												   @RequestParam("typeName") String typeName) {
		logger.info("try to update paper type by paperTypeId: " + paperTypeId + ", typeName: " + typeName);
		PaperType paperType = new PaperType();
		paperType.setId(paperTypeId);
		paperType.setTypeName(typeName);
		paperType.setUpdatedBy(getCurrentUser().getId());
		paperType.setUpdatedTime(new Date());
		paperTypeService.update(paperType);
		ResponseResult<Integer> rr = new ResponseResult<>(AppConsts.RESPONSE_STATUS_SUCCESS, 1);
		return rr;
	}

	@RequestMapping(value = "/paper-type", method = RequestMethod.DELETE)
	@ResponseBody
	public ResponseResult<Integer> deleteType(@RequestParam("paperTypeId") Integer paperTypeId) {
		logger.info("try to delete paper type by paperTypeId: " + paperTypeId);
		PaperType paperType = new PaperType();
		paperType.setId(paperTypeId);
		paperType.setUpdatedBy(getCurrentUser().getId());
		paperType.setUpdatedTime(new Date());
		paperTypeService.delete(paperType);
		ResponseResult<Integer> rr = new ResponseResult<>(AppConsts.RESPONSE_STATUS_SUCCESS, 1);
		return rr;
	}

}
